<?php
/**
 * Created by PhpStorm.
 * User: shkj
 * Date: 2020/4/15
 * Time: 10:59
 */

namespace app\api\model;


use think\Model;
use think\Db;
use think\facade\Request;

class Category extends Model
{
    public function img(){
        return $this->belongsTo('Image','img_id','id');
    }
    protected $autoWriteTimestamp = true;

    protected $createTime='create_time';
    protected $dateFormat='Y年m月d日';
    //开启自动设置
    protected $auto = [];
    protected $insert = ['create_tiame'];

    protected  $hidden = ['create_time'];


    public function select(){
        $cateRes=self::where(array('pid'=>0))->all([],'img');

        foreach ($cateRes as $k => $v) {
            $res[$k] = $v->hidden(['img_id','pid']);
            $cateRes[$k]['children']=self::where(array('pid'=>$v['id']))->all([],'img')->hidden(['img_id','pid']);
        }

        $cateRes = $cateRes->toArray();
        foreach ($cateRes as $key => $value){

            if(is_array($value['img'])) {
                foreach ($value['img'] as $k => $v) {
                    $value[$k] = $v;

                    $cateRes[$key] = $value;
                }
            }

            foreach ($value['children'] as $ik=>$iv){
                if(is_array($iv['img'])) {
                    foreach ($iv['img'] as $k => $v) {
                        $iv[$k]=$v;
                        $value[$ik] = $iv;
                        $cateRes[$key]['children'][$ik] = $iv;

                    }
                    unset($cateRes[$key]['children'][$ik]['img']);
                }
        
               $res = self::where(array('pid'=>$iv['id']))->all([],'img')->hidden(['img_id','pid']);
               foreach ($res as $keys => $values) {
                  $res[$keys]['images'] = $values['img']['images'];
                  unset($values['img']);
               }

 


                $cateRes[$key]['children'][$ik]['children'] = $res;

            }

            unset($cateRes[$key]['img']);
        }


        return_json(200,'查询成功',$cateRes) ;
    }

    public function all($pagenum,$pagesize,$type=0){
         $map = [];//将所有的查询条件封装到这个数组中
          //实现搜素功能
          $map =[];
          $keywords = Request::param('query');
          if(!empty($keywords)){
          //条件2
          $map[] = ['name','like','%'.$keywords.'%'];
        }
     
         $cateRes=self::where(array('pid'=>0))->where($map)->with('img')->page($pagesize,$pagenum)->hidden(['recommended'])->all();
       
        $count = self::where('pid',0)->count();


        foreach ($cateRes as $k => $v) {
            $res[$k] = $v->hidden(['img_id','recommended']);
            $cateRes[$k]['children']=self::where(array('pid'=>$v['id']))->all([],'img')->hidden(['img_id','pid']);
     
}
       foreach ($cateRes as $key => $value){

            if(is_array($value['img'])) {
                foreach ($value['img'] as $k => $v) {
                    $value[$k] = $v;

                    $cateRes[$key] = $value;
                }
            }

            foreach ($value['children'] as $ik=>$iv){
                if(is_array($iv['img'])) {
                    foreach ($iv['img'] as $k => $v) {
                        $iv[$k]=$v;
                        $value[$ik] = $iv;
                        $cateRes[$key]['children'][$ik] = $iv;

                    }
                    unset($cateRes[$key]['children'][$ik]['img']);
                }
        
               $res = self::where(array('pid'=>$iv['id']))->all([],'img')->hidden(['img_id','pid']);
               foreach ($res as $keys => $values) {
                  $res[$keys]['images'] = $values['img']['images'];
                  unset($values['img']);
               }

 


                $cateRes[$key]['children'][$ik]['children'] = $res;

            }

            unset($cateRes[$key]['img']);
        }
         
        $info = array(
          'data'=>$cateRes,
          'total'=>$count
            );

        return_json(200,'查询成功',$info) ;
    }

    public function recommend(){
        $cateRes=self::where('pid',0)->where('recommended','1')->all([],'img')->hidden(['img_id','pid','recommended']);
       

        $cateRes = $cateRes->toArray();
        foreach ($cateRes as $key => $value){

            if(is_array($value['img'])) {
                foreach ($value['img'] as $k => $v) {
                    $value[$k] = $v;

                    $cateRes[$key] = $value;
                }
            }

            unset($cateRes[$key]['img']);
        }


        return_json(200,'查询成功',$cateRes) ;
    }


    public function add($data)
    {
        $cate = self::where('name', $data['name'])->find();
        if ($cate) {
            return_json(400, '该分类已经存在',false);
        }
       
        $arr = array();
        $arr['images'] = $data['imageUrl'];

        $data['img_id'] = Db::name('image')->insertGetId($arr);//图片id


            $res = self::create($data);
            if ($res) {
                return_json(200, '添加成功',true);
            } else {
                return_json(400, '失败');
            }
        
    }

    public function del($id){

        $img = self::where('id',$id)->with('img')->find();
        //第三级直接删除
    
        //第二级
        if($img['pid'] != 0 && $img['level']==1){

        $res = self::where('pid',$id)->with('img')->all();
        foreach ($res as $key => $value) {
            $value->together('img')->delete();
           }

        }elseif($img['pid'] == 0 && $img['level']==0){
            //第一级
            $two = self::where('pid',$id)->with('img')->all();

            if($two){
                foreach ($two as $k => $v) {
            $three = self::where('pid',$v['id'])->with('img')->all();
               $v->together('img')->delete();
            foreach ($three as $key => $value) {
                $value->together('img')->delete();
            }
            }
              

            }
        }
         $res = $img->together('img')->delete();
        if($res){
            return_json(200,'删除成功');
        }else{
            return_json(400,'删除失败');
        }
    }

    public function detail($id){

        $res = $this->where('id',$id)->with('img')->find()->hidden(['pid','recommended','level'])->toArray();
        foreach ($res['img'] as $k=>$v){    
            $res[$k] = $v;
        }
        unset($res['img']);
        if($res){
            return_json(200,'查询成功',$res);
        }else{
            return_json(400,'查询失败',false);
        }
    }

    public function modify($id,$data)
    {

         $cate = self::where('name', $data['name'])->where('id', '<>', $id)->find();
        if ($cate) {
            return_json(400, '该分类已经存在',false);
        } 
     
        if(isset($data['imageUrl'])){ 
        // 删除原来的然后更新
        Image::where('images',$data['images'])->delete();
   
        $arr = array();
        $arr['images'] = $data['imageUrl'];
        $data['img_id'] = Db::name('image')->insertGetId($arr);//图片id
     
        unset($data['imageUrl']);   

       }
          unset($data['images']);   
       $this->perform($id,$data);

        }
    

    public function perform($id,$data){
      
            $res = self::where('id', $id)->update($data);
            if ($res) {
                return_json(200, '修改成功',true);
            } else {
                return_json(400, '修改失败',false);
            }
        
    }

}